<template>
  <a-modal
    :title="formTile + '自定义发送模板'"
    :visible="true"
    width="60%"
    :footer="null"
    @cancel="reset"
  >
    <div class="main">
      <a-card style="background:rgb(232, 232, 232)">
        <a-row
          type="flex"
          justify="start"
          align="top"
        >
          <a-col :span="24">
            <a-form
              :form="form"
              @submit="handleSubmit"
              :labelCol="formItemLayout.labelCol"
              :wrapperCol="formItemLayout.wrapperCol"
            >
              <div style="background: #fff;padding: 30px 0 20px 0;">
                <a-form-item
                  label="模板消息ID"
                  :required="true"
                >
                  <a-select
                    allow-clear
                    show-search
                    placeholder="请选择模板消息ID"
                    @change="changeTemplate"
                    :disabled="disabled"
                    optionFilterProp="children"
                    v-decorator="[
                  'id',
                  {
                    rules: [{ required: true, message: '请选择模板消息ID!' }]
                  }
                ]"
                  >
                    <a-select-option
                      :value="item.id"
                      v-for="(item,index)  in templateList"
                      :key="index"
                    >
                      {{ item.title }}
                    </a-select-option>
                  </a-select>
                </a-form-item>
                <a-form-item
                  label="模板名称"
                  :required="true"
                >
                  <a-input
                    allow-clear
                    placeholder="请输入模板名称"
                    :maxLength="40"
                    v-decorator="[
                  `templateName`,
                  {
                    validateTrigger: ['change', 'blur'],
                    rules: [
                      {
                        required: true,
                        whitespace: true,
                        message: '请输入模板名称！'
                      }
                    ]
                  }
                ]"
                  />
                </a-form-item>
                <a-form-item
                  label="模板创建人"
                  :required="true"
                >
                  <a-input
                    allow-clear
                    placeholder="请输入模板创建人"
                    :maxLength="40"
                    v-decorator="[
                  `creator`,
                  {
                    validateTrigger: ['change', 'blur'],
                    rules: [
                      {
                        required: true,
                        whitespace: true,
                        message: '请输入模板创建人！'
                      }
                    ]
                  }
                ]"
                  />
                </a-form-item>
                <a-form-item
                  label="推送主题"
                  :required="true"
                >
                  <a-input
                    allow-clear
                    placeholder="请输入推送主题"
                    v-decorator="[
                  `topic`,
                  {
                    validateTrigger: ['change', 'blur'],
                    rules: [
                      {
                        required: true,
                        whitespace: true,
                        message: '请输入推送主题！'
                      }
                    ]
                  }
                ]"
                  />
                </a-form-item>

                <a-form-item
                  label="模板跳转类型"
                  allow-clear
                >
                  <a-radio-group
                    name="radioGroup"
                    @change="changeRadio"
                    v-decorator="['type', { initialValue: 1, rules: [{ required: true, message: '请选择模板跳转类型!' }] }]"
                  >
                    <a-radio :value="1"> 跳转网页链接 </a-radio>
                    <a-radio :value="2"> 跳转小程序 </a-radio>

                  </a-radio-group>
                </a-form-item>
                <a-form-item
                  label="模板跳转链接"
                  :required="true"
                  v-if="radio == 1"
                >
                  <a-input
                    allow-clear
                    placeholder="请输入链接http://或https://开头"
                    :maxLength="40"
                    v-decorator="[
                  `viewPath`,
                    { rules:
                     [{ required: true, 
                     message: '请输入正确格式的模板跳转链接！',
                     whitespace: true, 
                     pattern: /http(s)?:\/\/[\w.]+[\w\/]*[\w.]*\??[\w=&\+\%]*/is }] }]"
                  />
                </a-form-item>
                <a-form-item
                  label="appid"
                  :required="true"
                  v-if="radio == 2"
                >
                  <a-input
                    allow-clear
                    placeholder="请输入appid"
                    :maxLength="40"
                    v-decorator="[
                  `miniProgramAppid`,
                  {
                    validateTrigger: ['change', 'blur'],
                    rules: [
                      {
                        required: true,
                        message: '请输入appid！'
                      }
                    ]
                  }
                ]"
                  />
                </a-form-item>
                <a-form-item
                  label="页面路径"
                  :required="true"
                  v-if="radio == 2"
                >
                  <a-input
                    allow-clear
                    placeholder="请输入页面路径"
                    :maxLength="400"
                    v-decorator="[
                  `miniProgramPagePath`,
                  {
                    validateTrigger: ['change', 'blur'],
                    rules: [
                      {
                        required: true,
                        message: '请输入页面路径！'
                      }
                    ]
                  }
                ]"
                  />
                </a-form-item>
              </div>
              <div style="background: #fff; padding: 30px 0 ;margin-top: 20px;">

                <a-form-item label="填充内容模板">
                  <a-row :gutter="16">
                    <a-col
                      class="gutter-row"
                      :span="12"
                    >
                      <div class="text">
                        <span
                          v-if="content"
                          class="content"
                        >
                          {{content}}
                        </span>
                        <span
                          v-else
                          style="color: #ee0a24;"
                        >
                          请选择模板消息ID
                        </span>
                      </div>
                    </a-col>
                    <a-col
                      class="gutter-row"
                      :span="12"
                    >
                      <div class="text">
                        <span
                          v-if="example"
                          class="content"
                        >
                          {{example}}
                        </span>
                        <span
                          v-else
                          style="color: #ee0a24; "
                        >
                          请选择模板消息ID
                        </span>
                      </div>
                    </a-col>

                  </a-row>

                </a-form-item>
                <a-form-item label="模板消息标签">
                  <a-select
                    allow-clear
                    show-search
                    placeholder="请选择模板消息标签"
                    @change="changeType"
                    v-model="newType"
                  >
                    <!-- <a-select-option
                      :value="item.id"
                      v-for="(item,index)  in labelList"
                      :key="index"
                    >
                      {{ item.name }}
                    </a-select-option> -->
                    <a-select-opt-group
                  
                      v-for="(item,index)  in labelList"
                      :key="index"
                    >
                     <span slot="label" style="color:#faad14;font-size:15px">{{item.label}}</span>
                      <a-select-option
                        :value="subitem.value"
                        v-for="(subitem,index)  in item.options"
                        :key="index"
                      >
                        {{subitem.label}}
                      </a-select-option>
                    </a-select-opt-group>
                  </a-select>
                </a-form-item>
                <a-form-item label="字段标签栏">
                  <div
                    v-if="fieldList==[] && add"
                    style="border: 1px solid #d9d9d9;height: 100px;padding: 20px;color: #ee0a24"
                  >
                    请先选择模板消息标签
                  </div>
                  <div
                    style="border: 1px solid #d9d9d9;height: 100px;padding: 20px;"
                    v-else
                  >
                    <span
                      v-for="(item,index) in fieldList"
                      :key="index"
                    >
                      <a-tag
                        color="blue"
                        @click="choose(item)"
                      >
                        {{item.fieldName}}
                      </a-tag>
                    </span>
                  </div>
                </a-form-item>

                <div
                  v-for="(item,index) in wxTemplateDetailList"
                  :key="index"
                >
                  <a-form-item
                    :label="item.businessKey"
                    :required="true"
                    style="display:flex;flex-direction: row;justify-content: center;"
                  >
                    <a-textarea
                      v-if="item.businessKey =='{{first.DATA}}' || item.businessKey =='{{remark.DATA}}'"
                      allow-clear
                      placeholder="请输入内容"
                      style="width:75%"
                      @click="leave"
                      @blur="handleInputBlur"
                      id="input"
                      v-decorator="[
                  `names[${index}]`,
                  {
                    initialValue: names[`${index}`],
                    validateTrigger: ['change', 'blur'],
                    rules: [
                      {
                        required: true,
                        whitespace: true,
                        message: '请输入内容'
                      }
                    ]
                  }
                ]"
                    >
                    </a-textarea>
                    <a-input
                      allow-clear
                      v-else
                      placeholder="请输入内容"
                      style="width:75%"
                      @click="leave"
                      @blur="handleInputBlur"
                      id="input"
                      v-decorator="[
                  `names[${index}]`,
                  {
                    initialValue: names[`${index}`],
                    validateTrigger: ['change', 'blur'],
                    rules: [
                      {
                        required: true,
                        whitespace: true,
                        message: '请输入内容'
                      }
                    ]
                  }
                ]"
                    />

                    <span :class="item.businessKey =='{{first.DATA}}' || item.businessKey =='{{remark.DATA}}'?'color':'colorinput'">
                      <colorPicker
                        style="border: 1px solid rgb(150, 151, 153);"
                        v-decorator="[
                  `color[${index}]`,
                  {
                    initialValue: color[`${index}`],
                    validateTrigger: ['change', 'blur'],
                    rules: [
                      {
                        required: true,
                        message: '请输入内容'
                      }
                    ]
                  }
                ]"
                      ></colorPicker>
                    </span>
                  </a-form-item>
                </div>

              </div>
              <a-row style="margin-top:10px">
                <a-col
                  :span="16"
                  :offset="18"
                  class="info-action"
                >
                  <a-button
                    @click="clear"
                    v-if="add"
                  >
                    重置
                  </a-button>
                  <a-button
                    :style="{ marginLeft: '8px' }"
                    type="primary"
                    html-type="submit"
                  >
                    保存
                  </a-button>
                </a-col>
              </a-row>
            </a-form>
          </a-col>
        </a-row>
      </a-card>
    </div>

  </a-modal>
</template>

<script>
import { postAction, getAction } from '@/api/manage'
export default {
  props: {
    template: {
      type: Object,
      default: null
    },
    appid: {
      type: String,
      default: null
    }
  },

  data() {
    return {
      urlKey: 'basemgt-wx',
      templateList: [],
      menuList: [],
      childrenList: [],
      id: '',
      leaveId: '',
      names: [],
      color: [],
      fieldList: [],
      labelList: [],
      disabled:false,
      businessId: '',
      wxTemplateDetailList: [],
      example: '',
      newType: undefined,
      content: '',
      radio: 1,
      formItemLayout: {
        labelCol: {
          xl: { span: 5 },
          xs: { span: 5 },
          sm: { span: 6 }
        },
        wrapperCol: {
          xl: { span: 16 },
          xs: { span: 12 },
          sm: { span: 12 }
        }
      },
      oldValue: '',
      add: false,
      textType: '',
      changeList: false,
      loading: true,
      templateId: '',
      title: '',
      placeholderVo: [],
      placeholderDetailList: [],
      form: this.$form.createForm(this)
    }
  },
  created() {
    const { template } = this.$props
    console.log(template)
    if (template) {
      this.formTile = '编辑'
      this.disabled = true
      this.radio = Number(template.type)
      this.id = template.id
      this.$nextTick(() => {
        this.templateId = template.templateId
        this.businessId = template.businessId
        this.childrenList = template.childrenList
        this.childrenList.map(item => {
          this.names.push(item.businessValue)
          this.color.push(item.color)
        })
        this.wxTemplateDetailList = this.childrenList
        this.form.setFieldsValue({
          templateName: template.templateName,
          topic: template.topic,
          creator: template.creator,
          type: Number(template.type),
          viewPath: template.viewPath,
          miniProgramAppid: template.miniProgramAppid,
          miniProgramPagePath: template.miniProgramPagePath,
          names: this.names,
          color: this.color
        })

        this.getDetail()
      })
      const remark = JSON.parse(template.childrenList[0].remark)
      if (remark.placeholderList[0].placeHolderId) {
        this.newType = remark.placeholderList[0].placeHolderId
        this.$nextTick(() => {
          this.changeType()
        })
      }
    } else {
      this.formTile = '新增'
      this.add = true
    }
  },
  mounted() {
    this.getMenuList()
    this.getLabelList()
  },
  watch: {
    appid() {
      this.getMenuList()
    }
  },
  methods: {
    reset() {
      this.form.resetFields()
      this.$emit('close')
    },
    clear() {
      this.form.resetFields()
    },
    leave(e) {
      e.preventDefault()
      const str = e.target.id
      this.leaveId = str.replace(/[^0-9]/gi, '')
    },
    handleInputBlur(e) {
      this.cursorIndex = e.srcElement.selectionStart
    },
    choose(item) {
      let old = this.form.getFieldsValue().names
      if (this.textType == 1) {
        old[this.leaveId] = old[this.leaveId].substr(0, this.cursorIndex) + item.fieldName + old[this.leaveId].substring(this.cursorIndex, old[this.leaveId].length)
      } else {
        old[this.leaveId] = old[this.leaveId].substr(0, this.cursorIndex) + item.fieldName + old[this.leaveId].substring(this.cursorIndex, old[this.leaveId].length)
      }
      this.form.setFieldsValue({
        names: old
      })
    },
    changeType() {
      const params = {
        id: this.newType
      }
      this.labelList.map(item => {
        if (item.id == this.newType) {
          this.textType = item.type
        }
      })
      getAction(`${this.urlKey}/WxPlaceHolder/findWxPlaceHolderDetailById`, params).then(data => {
        if (data.code == 200) {
          this.fieldList = data.data.placeholderDetailList
        } else {
          this.$message.warning(data.msg || data.message)
        }
      })
    },
    getDetail() {
      console.log(this.id)
      // const params = {
      //   id: this.id
      // }
      // getAction(`${this.urlKey}/WxMyTemplate/findWxMyTemplateDetailById`, params).then(data => {
      //   if (data.code == 200) {
      //     this.newType = data.data.childrenList[0].templatePlaceholderDTO.placeholderList[0].placeHolderId
      //     // if(this.newType){
      //     //   this.changeType()
      //     // }
      //   } else {
      //     this.$message.warning(data.msg || data.message)
      //   }
      // })
    },
    getMenuList() {
      const params = {
        appid: this.appid
      }
      postAction(`${this.urlKey}/WxStandardTemplate/findWxStandardTemplateList`, params).then(data => {
        if (data.code == 200) {
          this.templateList = data.data
          this.templateList.map(item => {
            if (item.templateId == this.templateId) {
              this.form.setFieldsValue({
                id: item.id
              })
              this.example = item.example
              this.content = item.content
              this.placeholderVo = item.placeholderVo
            }
          })
        } else {
          this.$message.warning(data.msg || data.message)
        }
      })
    },
    getLabelList() {
      const params = {
        // appid: this.appid
      }
      postAction(`${this.urlKey}/WxPlaceHolder/findNewWxPlaceHolderList`, params).then(data => {
        if (data.code == 200) {
          this.labelList = data.data
        } else {
          this.$message.warning(data.msg || data.message)
        }
        this.loading = false
      })
    },
    changeTemplate(value) {
      this.templateList.map(item => {
        if (value == item.id) {
          this.example = item.example
          this.content = item.content
          this.wxTemplateDetailList = item.wxTemplateDetailList
          let colors = []
          for (let index = 0; index < this.wxTemplateDetailList.length; index++) {
            const color = '#000000'
            colors.push(color)
          }
          this.color = colors
          this.form.setFieldsValue({
            color: colors
          })
        }
      })
      this.changeList = true
    },
    changeRadio(e) {
      this.radio = e.target.value
    },
    handleSubmit(e) {
      e.preventDefault()
      this.form.validateFields((err, values) => {
        if (!err) {
          this.submit(values)
        }
      })
    },
    submit(values) {
      let newNames = []
      values.names.map(item => {
        const str = {
          content: item
        }
        newNames.push(str)
      })
      newNames.map(item => {
        item.main = []
        this.fieldList.map(subitem => {
          if (item.content.indexOf(subitem.fieldName) > 0) {
            item.main.push(subitem)
          }
        })
      })
      if (this.childrenList.length) {
        this.wxTemplateDetailList = this.childrenList
      }
      this.wxTemplateDetailList.map((item, index) => {
        values.color.map((color, index1) => {
          if (index == index1) {
            item.color = color
          }
        })
        newNames.map((subitem, index1) => {
          if (index == index1) {
            item.businessValue = subitem.content
            const arr = []
            subitem.main.map(id => {
              const str = {
                id: id.id
              }
              arr.push(str)
            })
            const PlaceHolderInfoDTO = {
              placeHolderId: this.newType,
              placeholderDetailList: arr
            }
            const placeholderList = []
            placeholderList.push(PlaceHolderInfoDTO)
            const templatePlaceholderDTO = {
              placeholderList: placeholderList
            }
            item.templatePlaceholderDTO = templatePlaceholderDTO
          }
        })
      })
      this.templateList.map(item => {
        if (item.id == values.id) {
          this.templateId = item.templateId
          this.businessId = item.id
          this.title = item.title
        }
      })
      var params = {
        templateId: this.templateId,
        appid: this.appid,
        title: this.title,
        type: values.type,
        businessId: this.businessId,
        topic: values.topic,
        templateName: values.templateName,
        creator: values.creator,
        childrenList: this.wxTemplateDetailList
      }
      if (this.id) {
        params.id = this.id
      }
      console.log(values.type)
      if (values.type == 2) {
        params.miniProgramPagePath = values.miniProgramPagePath
        params.miniProgramAppid = values.miniProgramAppid
      } else {
        params.viewPath = values.viewPath
      }
      const api = this.add ? `${this.urlKey}/WxMyTemplate/insertWxMyTemplate` : `${this.urlKey}/WxMyTemplate/updateWxMyTemplate`
      postAction(api, params).then(data => {
        if (data.code == 200) {
          this.$message.success(this.add ? '新建模板成功！' : '修改成功！')
          this.reset()
        } else {
          this.$message.warning(data.msg || data.message)
        }
      })
    }
  }
}
</script>

<style scoped>
.text {
  font-size: 14px;
  padding: 10px;
  height: 230px;
  border: 1px dashed #969799;
  white-space: pre-line;
  line-height: 20px;
}
.color {
  border: 1px dashed #969799;
  padding: 6px 5px 3px 5px;
  top: -15px;
  left: 10px;
  position: relative;
}
.colorinput {
  border: 1px dashed #969799;
  padding: 6px 5px 3px 5px;
  left: 10px;
  position: relative;
}
.content {
  position: relative;
  top: -20px;
}
</style>
